<template><!-- 空车列表 -->
  <div class="empty-car-list">
    <div ref="dgtools" class="filter-container">
      <div class="dgts-fm">
        <el-date-picker
            v-model="dg.ps.setime"
            type="daterange"
            range-separator="至"
            start-placeholder="用车开始日期"
            end-placeholder="用车结束日期"
            style="width: 250px"
            value-format="yyyy-MM-dd"
        >
        </el-date-picker>

        <el-input
            style="width: 130px"
            placeholder="延长小时"
            maxlength="5"
            onkeyup="this.value = this.value.replace(/^(0+)|[^\d]+/g, '');"
            v-model="dg.ps.emptyHour"
        >
        </el-input>

        <el-select
            v-model="dg.ps.runArea"
            :placeholder="'可跑区域'"
            style="width: 150px"
        >
          <el-option
              v-for="(it, i) in serviceTypes"
              :key="i"
              :label="it.label"
              :value="it.val"
          >
          </el-option>
        </el-select>

        <el-button type="primary" icon="el-icon-search" @click="getDgList(0)">今天</el-button>
        <el-button type="primary" icon="el-icon-search" @click="getDgList(1)">明天</el-button>
        <el-button type="primary" icon="el-icon-search" @click="getDgList(2)">后天</el-button>
        <el-button type="primary" icon="el-icon-search" @click="getDgList()">搜索</el-button>

        <div class="ecl-now-time">
          <NowDateTime :format="'yyyy年MM月dd号 HH:mm:ss'"></NowDateTime>
        </div>
      </div>

      <div class="dgts-fm tj">
        <div class="tj-left">
          <div>
            <label>公司运力：{{dg.alUseCars}}/{{dg.totalCars}}<span>（已用车辆/总车辆）</span></label>
            <span class="progress"><el-progress :text-inside="true" :stroke-width="15" :percentage="dg.gsylProp" :color="'#409eff'"></el-progress></span>
          </div>
          <div>
            <label>业务运力：{{dg.alSendCars}}/{{dg.totalNeedCars}}<span>（已安排车辆/总需要车辆）</span></label>
            <span class="progress"><el-progress :text-inside="true" :stroke-width="15" :percentage="dg.ywylProp" :color="'#409eff'"></el-progress></span>
          </div>

          <div class="car-list">
            <span v-if="dg.list.length == 0" class="c-gray">没有空车数据！</span>
            <ul v-else>
              <li>
                <label>序号</label>
                <label></label>
                <label v-for="(n, i) in dg.carListNo" :key="i">{{n}}</label>
              </li>
              <li v-for="car in dg.list" :key="car.seats">
                <label>{{car.seats}}座</label>
                <div class="cars">
                  <div v-if="car.xjCars.length > 0">
                    <label>县际</label>
                    <label v-for="(c, i) in car.xjCars" :key="i" :style="{background: c.bgColor}">{{c.plateNum}}</label>
                    <label v-for="(c, i) in (dg.carListNo - car.xjCars.length)" :key="'_'+i"></label>
                  </div>
                  <div v-if="car.sjCars.length > 0">
                    <label>省市际</label>
                    <label v-for="(c, i) in car.sjCars" :key="i" :style="{background: c.bgColor}">{{c.plateNum}}</label>
                    <label v-for="(c, i) in (dg.carListNo - car.sjCars.length)" :key="'_'+i"></label>
                  </div>
                </div>
              </li>
            </ul>
          </div>

        </div>

        <div class="tj-right">
          <el-card style="min-height: 400px;">
            <el-tabs v-model="tabActiveName" :stretch="true">
              <el-tab-pane label="无主驾" name="tab_1">
                <el-empty description="暂无数据" v-if="noDriverList.length == 0"></el-empty>
                <ul class="no-driver-list" v-else>
                  <li v-for="(o, index) in noDriverList" :key="index" :title="o.status.text"><el-tag effect="dark">{{o.key}}</el-tag></li>
                </ul>
              </el-tab-pane>
              <el-tab-pane label="驾驶员休假" name="tab_2">
                <el-empty description="暂无数据" v-if="leaveDriverList.length == 0"></el-empty>
              </el-tab-pane>
              <el-tab-pane label="车辆维修" name="tab_3">
                <el-empty description="暂无数据" v-if="carRepairList.length == 0"></el-empty>
                <ul class="car-repair-list" v-else>
                  <li v-for="(o, index) in carRepairList" :key="index">{{index+1}}、<el-tag effect="dark">{{o.plateNum}}</el-tag> {{o.setime}}</li>
                </ul>
              </el-tab-pane>
              <el-tab-pane label="机动" name="tab_4">
                <el-empty description="暂无数据" v-if="flexDriverList.length == 0"></el-empty>
                <ul class="flex-driver-list" v-else>
                  <li v-for="(o, index) in flexDriverList" :key="index"><el-tag effect="dark">{{o.name}}-{{o.phone}}</el-tag></li>
                </ul>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </div>
      </div>
    </div>

    <!-- <div class="car-list">
      <span v-if="dg.list.length == 0" class="c-gray">没有空车数据！</span>
      <ul v-else>
        <li>
          <label>序号</label>
          <label></label>
          <label v-for="(n, i) in dg.carListNo" :key="i">{{n}}</label>
        </li>
        <li v-for="car in dg.list" :key="car.seats">
          <label>{{car.seats}}座</label>
          <div class="cars">
            <div v-if="car.xjCars.length > 0">
              <label>县际</label>
              <label v-for="(c, i) in car.xjCars" :key="i" :style="{background: c.bgColor}">{{c.plateNum}}</label>
              <label v-for="(c, i) in (dg.carListNo - car.xjCars.length)" :key="'_'+i"></label>
            </div>
            <div v-if="car.sjCars.length > 0">
              <label>省市际</label>
              <label v-for="(c, i) in car.sjCars" :key="i" :style="{background: c.bgColor}">{{c.plateNum}}</label>
              <label v-for="(c, i) in (dg.carListNo - car.sjCars.length)" :key="'_'+i"></label>
            </div>
          </div>
        </li>
      </ul>
    </div> -->
  </div>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog';
import NowDateTime from '@/components/NowDateTime';
import moment from 'moment'
import * as carService from '@/api/services/car.service';

export default {
  name: 'EmptyCarList',
  mixins: [ ],
  directives: { elDragDialog },
  components: { NowDateTime },
  data() {
    return {
      // 业务类型
      serviceTypes: [
        {val: '', label: '可跑区域（全部）'},
        {val: 'COUNTY_SER', label: '县际业务'},
        {val: 'CITY_SER', label: '市际业务'},
        {val: 'PROVINCE_SER', label: '省际业务'},
      ],
      // 右边选择查询的tab名称
      tabActiveName: 'tab_1',
      // 无主驾
      noDriverList: [],
      // 驾驶员休假
      leaveDriverList: [],
      // 车辆维修
      carRepairList: [],
      // 机动(顶班驾驶员)
      flexDriverList: [],
      // 表格数据列表参数
      dg: {
        tbName: 'emptyCarListTb',
        loading: true,
        ps: { // 过滤参数
          page: 1, rows: 20,
          // 用车起止时间段
          setime: [],
          // 延长小时
          emptyHour: '',
          // 可跑区域
          runArea: '',
          // 哪一天
          whichDay: '',
        },
        total: 0,
        list: [],

        // 车辆列表编号
        carListNo: 0,
        // 总车辆数
        totalCars: 0,
        // 已用车辆数
        alUseCars: 0,
        // 公司运力
        gsylProp: 0,
        // 总需要车辆数
        totalNeedCars: 0,
        // 已安排车辆数
        alSendCars: 0,
        // 业务运力
        ywylProp: 0,
      },

    }
  },
  beforeRouteEnter(to,form,next) {
    next(vm => {
      vm.dg.ps.setime = ''
      let query = vm.$route.query
      if (query.type === '24小时空车查询') {
        let time = moment().format("yyyy-MM-DD")
        vm.dg.ps.setime = [`${time} 00:00:00`, `${time} 23:59:59`]
      }
      if (query.type === '30天空车查询') {
        let startTime = moment().subtract(0, "days").format("YYYY-MM-DD") + " 00:00:00"
        let endTime = moment().subtract(-29, "days").format("YYYY-MM-DD") + " 23:59:59"
        vm.dg.ps.setime = [startTime, endTime]
      }
    })
  },
  created() {
    const that = this;

    that.getDgList();
  },
  methods:{
    /**
     * 获取-背景颜色
     * @param state 车辆状态 0是正常，大于0就是订单数，repair是维修，leave是请假
     * @param text 说明文本
     */
    getBgColor(state, text){
      const that = this;

      let kv = {
        // 正常
        zc: '#FFFFFF',
        // 出车
        cc: '#8dea49',
        // 无主驾
        wzj: '#66CCFF',
        // 驾驶员休假
        xj: '#FF00FF',
        // 车辆维修
        wx: '#FFFF00'
      };

      let res = kv['zc']; // 颜色结果 默认正常
      if(!that.FV.isNumber(state)){
        // 状态码不是数字
        if(state == 'repair'){
          res = kv['wx'];
        }else if(state == 'leave'){
          res = kv['xj'];
        }
      }else{
        // 状态码是数字
        let _state = parseInt(state);

        if(_state > 0 && text == '无主驾'){
          res = kv['wzj'];
        }else if(_state > 0 && text != '无主驾'){
          res = kv['cc'];
        }
      }

      return res;
    },
    /**
     * 获取-驾驶员状态
     * @param code 状态码
     */
    driverStatusText(code){
      // 0是正常 leave是请假 repair是维修，其余则是日程个数
      let codeText = '';
      code = code+'';
      switch(code){
        case '0':
          codeText = '正常';
          break;
        case 'leave':
          codeText = '请假';
          break;
        case 'repair':
          codeText = '维修';
          break;
        default:
          codeText = code+'个日程';
      }
      console.log('结果', code, codeText);
      return codeText;
    },
    /**
     * 获取数据列表
     * @param timeType 时间类型
     */
    getDgList(timeType){
      const that = this, ps = that.U.scopy(that.dg.ps);

      // 参数处理
      if(ps.setime && ps.setime.length == 2){
        ps.usTime = ps.setime[0];
        ps.ueTime = ps.setime[1];
      }else{
        ps.usTime = "";
        ps.ueTime = "";
        delete ps.setime;
      }

      if(timeType){
        ps.whichDay = timeType;

        // 0-今天；1-明天；2-后天；
        let setime = that.U.getSEToday(timeType);

        ps.usTime = setime[0].split(' ')[0];
        ps.ueTime = setime[1].split(' ')[0];
      }

      let loading = that.U.qloading('数据请求中...');
      carService.getEmptyCarList(ps).then(res => {
        that.U.qclose(loading);

        if(!res || res.code != 1){
          that.U.qerror('数据请求失败');
        }else{
          // 车辆座位数
          let list = res.seatList || [];

          let reslist = [], maxNo = 0;// 结果数组, 最多的车辆数字
          for(let key in list){
            let it = list[key], sjCars = [], xjCars = [];

            // 省市际车辆
            let sjlist = it.find(a => a.id.indexOf('sj') != -1);
            if(sjlist.other.length > maxNo) maxNo = sjlist.other.length;
            sjlist.other.forEach(a => {
              // 获取-背景颜色
              let colorCode = that.getBgColor(a.id.split('=')[1], a.text);
              sjCars.push({
                plateNum: a.id.split('=')[0],
                state: a.id.split('=')[1],
                text: a.text,
                bgColor: colorCode,
              });
            });

            // 县际车辆
            let xjlist = it.find(a => a.id.indexOf('xj') != -1);
            if(xjlist.other.length > maxNo) maxNo = xjlist.other.length;
            xjlist.other.forEach(a => {
              // 获取-背景颜色
              let colorCode = that.getBgColor(a.id.split('=')[1], a.text);
              xjCars.push({
                plateNum: a.id.split('=')[0],
                state: a.id.split('=')[1],
                text: a.text,
                bgColor: colorCode,
              });
            });

            reslist.push({
              seats: key,
              sjCars: sjCars,
              xjCars: xjCars
            });
          }

          console.log('车辆列表', reslist, maxNo);

          that.dg.carListNo = maxNo;
          that.dg.list = reslist;


          // 其他数据
          that.dg.totalCars = parseInt(res.totalCar);
          that.dg.alUseCars = parseInt(res.alUseCar);
          // 公司运力百分比计算
          that.dg.gsylProp = that.dg.alUseCars == 0 ? 0 : that.U.num((that.dg.alUseCars/that.dg.totalCars)*100, 1);

          that.dg.totalNeedCars = parseInt(res.totalNeedCar);
          that.dg.alSendCars = parseInt(res.alSendCar);
          // 业务运力百分比计算
          that.dg.ywylProp = that.dg.alSendCars == 0 ? 0 : that.U.num((that.dg.alSendCars/that.dg.totalNeedCars)*100, 1);


          // 右边面板显示数据
          // 无主驾
          let noDriverList = [];
          if(res.noDriver.length > 0){
            res.noDriver.forEach(it => {
              let stausCode = it.split('=')[1], statusText = that.driverStatusText(stausCode);
              noDriverList.push({
                key: it.split('=')[0],
                status: {val: stausCode, text: statusText}
              });
            });
            console.log('无主驾', noDriverList);
            that.noDriverList = noDriverList;
          }

          // 休假驾驶员
          let leaveDriverList = [];
          if(res.leaveDriver.length > 0){
            res.leaveDriver.forEach(it => {
              leaveDriverList.push({
                key: '',
                val: ''
              });
            });
            console.log('休假驾驶员', leaveDriverList);
            that.leaveDriverList = leaveDriverList;
          }

          // 车辆维修
          let carRepairList = [];
          if(res.repairCar.length > 0){
            res.repairCar.forEach(it => {
              let stausCode = it.split('=')[1], statusText = that.driverStatusText(stausCode);
              carRepairList.push({
                plateNum: it.split('=')[0],
                status: {val: stausCode, text: statusText},
                setime: it.split('=')[2]
              });
            });

            console.log('车辆维修', carRepairList);
            that.carRepairList = carRepairList;
          }

          // 机动（顶班驾驶员）
          let flexDriverList = [];
          if(res.flexDriver.length > 0){
            res.flexDriver.forEach(it => {
              flexDriverList.push({
                phone: it.split('-')[1],
                name: it.split('-')[0],
              });
            });

            console.log('顶班驾驶员', flexDriverList);
            that.flexDriverList = flexDriverList;
          }

        }
      }).catch(() => { that.U.qclose(loading); });
    },

  }
}
</script>

<style lang="less" scoped>
.empty-car-list ::v-deep{
  .ecl-now-time{
    position: absolute;
    top: 0;
    right: 10px;
  }

  .tj{ // 统计
    display: block;
    height: 30px;

    .tj-left{
      float: left;
      height: 30px;

      &>div{
        float: left;
        margin-right: 20px;
        font-size: 12px;

        label{
          font-weight: normal;
          color: #000;

          span{
            color: #666;
          }
        }

        .progress{
          display: inline-block;
          height: 10px;
          width: 200px;

          .el-progress-bar__innerText{
            color: #333;
          }
        }

      }
    }

    .tj-right{
      float: right;
      margin-top: 35px;

      .el-tab-pane{
        width: 410px;
      }

      .no-driver-list{
        margin: 0px;
        padding: 0px;
        display: flex;
        flex-wrap: wrap;
        width: 410px;
        overflow-y: auto;
        max-height: 80vh;

        li{
          font-size: 12px;
          margin: 0px;
          list-style: none;
          width: 80px;
          text-align: center;
          // cursor: pointer;
        }
      }

      .car-repair-list{
        margin: 0px;
        padding: 0px;

        li{
          font-size: 12px;
          margin: 0px;
          list-style: none;
          text-align: left;
        }
      }

      .flex-driver-list{
        margin: 0px;
        padding: 0px;
        display: flex;
        flex-wrap: wrap;
        width: 410px;
        overflow-y: auto;
        max-height: 80vh;

        li{
          font-size: 12px;
          margin: 0px;
          list-style: none;
          text-align: center;
          margin: 0 5px;
        }
      }

      .tj-color-explain{
        padding: 0px;
        margin: 0px;
        height: 30px;

        li{
          margin-left: 30px;
          float: left;
          list-style: none;
          font-size: 12px;

          u{
            border-radius: 50%;
            display: inline-block;
            width: 8px;
            height: 8px;
            margin-right: 5px;
          }
        }
      }
    }
  }

  @borderColor: #1890ff;
  .car-list{
    ul{
      margin: 0;
      padding: 0;
      height: calc(100vh - 170px);
      overflow: auto;
      min-width: 1100px;

      li{
        float: left;
        border-top: 1px solid @borderColor;
        list-style: none;

        // 第一列
        &:first-child{
          border-left: 1px solid @borderColor;

          // 第二行第一个
          &>label:nth-child(2){
            background-color: #efefef;
          }
        }

        // 不是第一列
        &:not(:first-child){
          .cars{
            display: flex;

            &>div{
              flex: 1;

              &>label:first-child{
                background-color: #efefef;
              }

              label{
                padding: 0 3px;
              }
            }
          }
        }

        // 第一行
        &>label:first-child{
          background: #393B6A;
          color: #fff;
        }

        label{
          font-size: 12px;
          display: block;
          height: 20px;
          line-height: 20px;
          font-weight: normal;
          border-right: 1px solid @borderColor;
          border-bottom: 1px solid @borderColor;
          text-align: center;

          &:not(:first-child){
            width: 70px;
          }
        }
      }
    }
  }

}
</style>
